'''
给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。
'''
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        '''
            借助k个一组反转的思想，就是2个一组反转
        '''
        if head is None:
            return None
        a = b = head
        for i in range(2):
            b = b.next
        newhead = self.reverse(head,a,b)
        a.next = self.swapPairs(b)
        return newhead
    

    #反转区间内的链表
    def reverse(self,head,a,b):
        t= None
        p = q = head
        while p != b:
            q = p.next
            p.next = t
            t = p
            p = q
        return t
    
    def swapPairs2(self, head: Optional[ListNode]) -> Optional[ListNode]:
        p  = head
        newHead = head.next
        t = None
        while p.next:
            q = p.next.next
            t = p.next
            t.next = p
            p.next = q
            p = q
        return newHead